//
// Created by ziya on 22-9-13.
//

#include "../../include/core/buffer.h"

extern char* open_stream(char* filepath, int* p_filesize);

buffer_t* buffer_create(const char* filepath) {
    buffer_t* buffer = NULL;

    // 在堆中创建buffer势力
    buffer = Calloc(1, sizeof(buffer_t));

    // 在buffer中保存filepath
    buffer->filepath = Calloc(1, strlen(filepath));

    memcpy(buffer->filepath, filepath, strlen(filepath));

    // 初始化buffer相关属性
    buffer->off = 0;
    buffer->data = open_stream(filepath, &(buffer->filesize));

    return buffer;
}

u_char buffer_read1(buffer_t* buffer) {
    assert(NULL != buffer, "buffer is null");
    assert(NULL != buffer->data, "buffer.data is null");

    u_char ret = *(u_char*)(buffer->data + buffer->off);
    buffer->off += 1;

    return ret;
}

u_short buffer_read2(buffer_t* buffer) {
    assert(NULL != buffer, "buffer is null");
    assert(NULL != buffer->data, "buffer.data is null");

    ushort ret = *(ushort*)(buffer->data + buffer->off);
    buffer->off += 2;

    return ret;
}

u_int32_t buffer_read4(buffer_t* buffer) {
    assert(NULL != buffer, "buffer is null");
    assert(NULL != buffer->data, "buffer.data is null");

    u_int32_t ret = *(u_int32_t*)(buffer->data + buffer->off);
    buffer->off += 4;

    return ret;
}

u_int64_t buffer_read8(buffer_t* buffer) {
    assert(NULL != buffer, "buffer is null");
    assert(NULL != buffer->data, "buffer.data is null");

    u_int64_t ret = *(u_int64_t*)(buffer->data + buffer->off);
    buffer->off += 8;

    return ret;
}

void buffer_copy(buffer_t* buffer, char* dest, size_t size) {
    assert(NULL != buffer, "buffer is null");
    assert(NULL != buffer->data, "buffer.data is null");
    assert(NULL != dest, "dest is null");
    assert(0 != size, "size == 0");

    memcpy(dest, buffer->data + buffer->off, size);

    buffer->off += size;
}

void buffer_reset(buffer_t* buffer) {
    assert(NULL != buffer, "buffer is null");

    buffer->off = 0;
}